import { http } from '@/request/http'
import type { UserVO } from '@/request/api/user'
import { initUserVO } from '@/request/api/user'
import type { PageDTO, PageVO } from '@/type/type'
import type { MakeOptional } from '@/type'

type BaseComment = {
  id: number
  // 源ID（评论来源）
  sourceId: number
  // 楼层评论（该ID和评论ID相同时无楼层，自己为楼层）
  floorId: number
  // 点赞量
  likeCount: number
  // 内容
  content: string
  // 图片
  imgUrl: string
  // 创建时间
  createTime: Date
}

export type CommentDTO = MakeOptional<BaseComment> & {
  // 用户ID
  userId: number | undefined
  // 父评论用户ID（create_by和该ID相同时未回复评论）
  parentUserId: number | undefined
}

export type CommentVO = BaseComment & {
  user: UserVO
  // 父用户
  parentUser: UserVO
  // 子评论
  children: CommentVO[]
}

export const initCommentDTO = (): CommentDTO => {
  return {
    id: undefined,
    userId: undefined,
    sourceId: undefined,
    floorId: undefined,
    parentUserId: undefined,
    likeCount: undefined,
    content: undefined,
    imgUrl: undefined
  }
}

export const initCommentVO = (): CommentVO => {
  return {
    id: 0,
    user: initUserVO(),
    sourceId: 0,
    floorId: 0,
    parentUser: initUserVO(),
    likeCount: 0,
    content: '',
    imgUrl: '',
    createTime: new Date(),
    children: []
  }
}

export const addCommentApi = (data: FormData) => {
  return http<boolean>({
    url: `/comment/insert`,
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    data: data
  })
}

export const getCommentPageApi = (page: PageDTO) => {
  return http<PageVO<CommentVO>>({
    url: `/comment/page`,
    method: 'get',
    params: {
      dto: JSON.stringify(page)
    }
  })
}

export const getCommentAdminPageApi = (page: PageDTO) => {
  return http<PageVO<CommentVO>>({
    url: `/admin/comment/page`,
    method: 'get',
    params: {
      dto: JSON.stringify(page)
    }
  })
}

export const delCommentApi = (ids: number[]) => {
  return http<boolean>({
    url: `/admin/comment/delete`,
    method: 'delete',
    data: ids
  })
}
